package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author zengjinjin
 * @version 1.0
 * @date 2021/11/21 17:39
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{},异常类型{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> repoMap = null;
        if (result.hasErrors()) {
            List<FieldError> allErrors = result.getFieldErrors();
            repoMap = allErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (x, y) -> x));
        }
        return R.error(BizCodeEnum.VALID_EXCEPTION).put("date", repoMap);
    }

//    @ExceptionHandler(Throwable.class)
//    public R handleException(Throwable throwable) {
//        log.error("异常问题{},异常类型{}", throwable.getMessage(), throwable.getClass());
//        return R.error(BizCodeEnum.UNKNOW_EXCEPTION);
//    }
}
